package com.touch.app.common.util;

import cn.hutool.core.util.RuntimeUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;

public class PythonUtils {

    private PythonUtils(){}

    private static final String PYTHON_WINDOWS = "python";
    private static final String PYTHON_LINUX_2 = "python";
    private static final String PYTHON_LINUX_3 = "python3";

    public static JSONObject exec(String filePath, String args, String pythonVersion) {
        String cmd = getPythonEnv(pythonVersion) +
                " " +
                filePath +
                " " +
                args;
        JSONObject json = new JSONObject();
        Process process = RuntimeUtil.exec(cmd);
        try {
            process.waitFor();
        } catch (Exception e) {
            Thread.currentThread().interrupt();
        }
        String errorResult = RuntimeUtil.getErrorResult(process, StandardCharsets.UTF_8);
        String result = RuntimeUtil.getResult(process, StandardCharsets.UTF_8);
        json.put("code", 200);
        json.put("data", result);
        json.put("error", errorResult);
        return json;
    }

    private static String getPythonEnv(String pythonVersion) {
        String os = System.getProperty("os.name");
        if (os.contains("Windows")) {
            return PYTHON_WINDOWS;
        }
        if (StringUtils.hasLength(pythonVersion)) {
            pythonVersion = pythonVersion.replaceAll("\\s", "");
            if (StringUtils.hasLength(pythonVersion) && pythonVersion.startsWith("3")) {
                return PYTHON_LINUX_3;
            }
        }
        return PYTHON_LINUX_2;
    }
}
